package com.start.captcha.web;

import cn.hutool.core.io.IoUtil;
import com.start.captcha.StartCaptcha;
import com.start.common.exceptions.StartBusException;
import com.start.common.tools.StartRedisTools;
import com.start.common.tools.UUIdTools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Service
public class StartCaptchaService {


    @Autowired
    private StartRedisTools redisTools;

    @Autowired
    private CaptchaAutoConfiguration captchaAutoConfiguration;

    /**
     * 创建验证码
     *
     * @param prefix
     * @return
     */

    public CaptchaResult createCaptcha(String prefix) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        StartCaptcha captcha = StartCaptcha.require(outputStream).build();
        captcha.finish();
        String code = captcha.getCode();
        String captchaCode = UUIdTools.createId32();
        String key = getRedisKey(prefix, captchaCode);
        CaptchaResult result = new CaptchaResult();
        result.setCaptchaCode(captchaCode);
        result.setCaptchaImg(new String(Base64Utils.encode(outputStream.toByteArray()), StandardCharsets.UTF_8));
        IoUtil.close(outputStream);
        redisTools.set(key, code, captchaAutoConfiguration.getExpire() * 60);
        return result;
    }

    /**
     * 比对验证码
     *
     * @param prefix
     * @param captchaCode   验证码code
     * @param userInputCode 用户输入的验证码信息
     * @return
     */
    public boolean verification(String prefix, String captchaCode, String userInputCode) {
        String redisKey = getRedisKey(prefix, captchaCode);
        if (StringUtils.isEmpty(userInputCode)) {
            throw new StartBusException("请输入验证码");
        }
        if (redisTools.hasKey(redisKey))
            return false;
        Object o = redisTools.get(redisKey);
        if (o == null) {
            redisTools.del(redisKey);
            return false;
        }
        return Objects.equals(o, userInputCode);
    }

    private String getRedisKey(String prefix, String captchaCode) {
        if (StringUtils.isEmpty(prefix)) {
            prefix = "captchaCode:";
        }
        if (!prefix.endsWith(":")) {
            prefix += ":";
        }
        return captchaAutoConfiguration.getRedisKey() + prefix + captchaCode;
    }
}
